package impl

import (
	"context"
	"errors"
	"github.com/sirupsen/logrus"
	"monoblog/common/register"
	"monoblog/domain/dao"
	"monoblog/domain/dto"
	"monoblog/domain/model"
	"monoblog/domain/service"
	"time"
)

func init() {
	register.RegisterInstance[service.SectionService]("SectionService", func() service.SectionService {
		return &SectionServiceImpl{
			sectionRepository: dao.NewSectionRepository(),
			articleRepository: dao.NewArticleRepository(),
		} // 返回唯一实例
	})
}

type SectionServiceImpl struct {
	sectionRepository *dao.SectionRepository
	articleRepository *dao.ArticleRepository
}

func (s *SectionServiceImpl) Add(ctx context.Context, form dto.SectionReqForm) (string, error) {
	var userId = form.LoginUser.UID

	//判断是否存在
	exists, _ := s.sectionRepository.ExistsByName("", form.Name, userId)
	if exists {
		return "", errors.New("section name is duplicated")
	}

	section := &model.Section{
		UserId:      userId,
		Name:        form.Name,
		Description: form.Description,
		Photo:       form.Photo,
		CreateTime:  time.Now(),
	}

	err := s.sectionRepository.Add(section)
	if err != nil {
		logrus.Errorf("[aid: %s] Add section failed: %v", ctx.Value("aid"), err.Error())
		return "", err
	}
	logrus.Infof("[aid: %s] Add section success: %v", ctx.Value("aid"), section.ID)
	return section.ID, nil
}

func (s *SectionServiceImpl) UpdateByID(ctx context.Context, id string, form dto.SectionReqForm) error {
	var userId = form.LoginUser.UID

	section := &model.Section{
		Name:        form.Name,
		Description: form.Description,
	}
	//判断是否存在
	exists, _ := s.sectionRepository.ExistsByName(id, form.Name, userId)
	if exists {
		return errors.New("section name is duplicated")
	}

	err := s.sectionRepository.UpdateByID(id, *section)
	return err
}

func (s *SectionServiceImpl) DeleteByID(ctx context.Context, id string) error {
	//先判断section下面有没有文章，如果有的话，不能删除
	count, err := s.articleRepository.FindCountBySectionID(id, false)
	if err != nil {
		logrus.Errorf("[aid: %s] findCountBySectionID failed: %v", ctx.Value("aid"), err.Error())
		return err
	}
	if count > 0 {
		return errors.New("section has articles, can not be deleted")
	}

	err = s.sectionRepository.DeleteByID(id) //删除section
	return err
}

func (s *SectionServiceImpl) FindByID(ctx context.Context, id string) (*model.Section, error) {
	section, err := s.sectionRepository.FindByID(id)

	//查询section下面文章数量
	count, err := s.articleRepository.FindCountBySectionID(id, false)
	if err != nil {
		logrus.Errorf("[aid: %s] findCountBySectionID failed: %v", ctx.Value("aid"), err.Error())
	}
	section.BlogCount = count
	return section, err
}

func (s *SectionServiceImpl) FindList(ctx context.Context) ([]*model.Section, error) {
	sections, _, err := s.sectionRepository.FindList()

	//查询section下面文章数量
	for _, section := range sections {
		count, err := s.articleRepository.FindCountBySectionID(section.ID, false)
		if err != nil {
			logrus.Errorf("[aid: %s] findCountBySectionID failed: %v", ctx.Value("aid"), err.Error())
		}
		section.BlogCount = count //注意 section是指针才能赋值
	}
	return sections, err
}

func (s *SectionServiceImpl) SectionsByUserId(ctx context.Context, userId string) ([]*model.Section, error) {
	sections, _, err := s.sectionRepository.FindListByUserId(userId)

	//查询section下面文章数量
	for _, section := range sections {
		count, err := s.articleRepository.FindCountBySectionID(section.ID, false)
		if err != nil {
			logrus.Errorf("[aid: %s] findCountBySectionID failed: %v", ctx.Value("aid"), err.Error())
		}
		section.BlogCount = count //注意 section是指针才能赋值
	}
	return sections, err
}
